#include "Delay.h"

uint32_t uwTick = 0;  // 全局毫秒计数器

// SysTick中断服务函数（每1ms触发一次）
void SysTick_Handler(void) {
    uwTick++;  // 毫秒计数器递增
}

// 初始化SysTick定时器（1ms中断一次）
void Delay_Init(void) {
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);  // 时钟源为72MHz
    uint32_t ticks = SystemCoreClock / 1000;  // 1ms对应的时钟周期（72000）
    SysTick_Config(ticks);  // 配置SysTick
    NVIC_SetPriority(SysTick_IRQn, NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 15, 15));
}

// 获取当前毫秒级时间戳
uint32_t Delay_GetTick(void) {
    return uwTick;
}

// 其他函数（Delay_Ms/Us/S）保持不变...
void Delay_Ms(uint32_t ms) {
    uint32_t tickstart = Delay_GetTick();
    uint32_t wait = ms;
    if (wait < 0xFFFFFFFF) wait += 1;
    while ((Delay_GetTick() - tickstart) < wait);
}

void Delay_Us(uint32_t us) {
    uint32_t start = SysTick->VAL;
    uint32_t reload = SysTick->LOAD;
    uint32_t ticks_needed = (us * 72 + 999) / 1000;
    while (1) {
        uint32_t current = SysTick->VAL;
        uint32_t elapsed = (current <= start) ? (start - current) : (reload - current + start);
        if (elapsed >= ticks_needed) break;
    }
}

void Delay_S(uint32_t s) {
    Delay_Ms(s * 1000);
}
